package task1205.Demo.Demo5;

import task1205.Demo.Demo3.*;
import task1205.Demo.Demo2.Demo1;
import task1205.Demo.Demo4.CallService;
import task1205.Demo.Demo4.NetService;
import task1205.Demo.Demo4.SendService;

import java.io.*;
import java.util.*;

public class CardUtil {
    Map<String, Demo2> demo2Map = new HashMap<>();
    Map<String, List<task1205.Demo.Demo3.Demo1>> demo1Map = new HashMap<>();
    List<Demo3> demo3s = new ArrayList<>();
    public void init(){
        Demo2 d1 = new Demo2("何玲铃","123","13965756432",new TalkPackage(),58.0,42.0);
        Demo2 d2 = new Demo2("黄玲玲","123","13956712467",new NetPackage(),68.0,32.0);
        Demo2 d3 = new Demo2("朱蓉荣","123","13965751234",new SuperPackage(),78.0,22.0);
        Demo2 d4 = new Demo2("桃跑跑","123","13912346432",new TalkPackage(),78.0,2.0);
        d4.setConsumAmount(98.0);
        d4.setMoney(100);
        d4.setRealTalkTime(500);
        demo2Map.put("13965756432",d1);
        demo2Map.put("1395671246",d2);
        demo2Map.put("13965751234",d3);
        demo2Map.put("13912346432",d4);
    }

    public void initScenes(){
        demo3s.add(new Demo3("通话",50,"问候客户，谁知其如此难缠通话90分钟"));
        demo3s.add(new Demo3("通话",30,"询问妈妈身体状况，本地通话30分钟"));
        demo3s.add(new Demo3("短信",5,"参与环境保护实施方案问卷调查 发送短信5条"));
        demo3s.add(new Demo3("短信",50,"通知朋友手机换号，发送短信50条"));
        demo3s.add(new Demo3("上网",1*1024,"和女友微信视频聊天   使用流量1G"));
        demo3s.add(new Demo3("上网",2*1024,"晚上手机在线看韩剧，不留神睡着啦！ 使用流量 2G"));
    }

    public boolean isExistCard(String number,String passWord){
        Set<String> numbers = demo2Map.keySet();
        Iterator<String> it = numbers.iterator();
        while (it.hasNext()){
            String searchNum = it.next();
            if (searchNum.equals(number) &&(demo2Map.get(searchNum)).getPassWord().equals(passWord)){
                return true;
            }
        }
        return false;
    }
    public boolean isExistCard(String searchNumber){
        Set<String> numbers = demo2Map.keySet();
        for (String number : numbers){
            if (number.equals(searchNumber)){
                return true;
            }
        }
        return false;
    }

    public String createNumber(){
        Random random = new Random();
        boolean isExist = false;
        String number = "";
        int temp = 0;
        do {
            do {
                temp = random.nextInt(100000000);
            }while (temp<10000000);
            number = "123"+temp;
            Set<String> cardNumbers = demo2Map.keySet();
            for (String cardNumber : cardNumbers){
                if (number.equals(cardNumber)){
                    isExist = true;
                    break;
                }
            }
        }while (isExist);
        return number;
    }

    public String[] getNewNumbers(int cout){
        String[] numbers = new String[cout];
        for (int i = 0; i < cout; i++) {
            numbers[i] = createNumber();
        }
        return numbers;
    }

    public void addCard(Demo2 demo2){
        demo2Map.put(demo2.getCardNumber(),demo2);
        System.out.println("注册成功");
        demo2.showMeg();
    }

    public void delCard(String delNumber){
        if (isExistCard(delNumber)){
            demo2Map.remove(delNumber);
            System.out.println("卡号"+delNumber+"办理退网成功");
        }else {
            System.out.println("对不起，该卡号未注册，不能办理退网！");
        }
    }

    public void showRemainDetail(String searchNumber){
        Demo2 demo2;
        int remaintalkTime;
        int remainSmsCount;
        int remainFlow;
        StringBuffer meg = new StringBuffer();
        demo2 = demo2Map.get(searchNumber);
        meg.append("您的卡号是"+searchNumber+",套餐内剩余：\n");
        SercicePackage pack = demo2.getSerPackage();
        if (pack instanceof TalkPackage){
            TalkPackage cardPack = (TalkPackage) pack;
            remaintalkTime = cardPack.getTalkTime()>demo2.getRealTalkTime()? cardPack.getTalkTime()
                    - demo2.getRealTalkTime() : 0;
            meg.append("通话时长：").append(remaintalkTime).append("分钟\n");
            remainSmsCount = cardPack.getSmsCount() > demo2
                    .getRealSMSCount() ? cardPack.getSmsCount()
                    - demo2.getRealSMSCount() : 0;
            meg.append("短信条数：" + remainSmsCount + "条");
        }else if (pack instanceof NetPackage) {
            NetPackage cardPack = (NetPackage) pack;
            remainFlow = cardPack.getFlow() > demo2.getRealFlow() ? cardPack
                    .getFlow() - demo2.getRealFlow() : 0;
            meg.append("上网流量：" + task1205.Demo.Demo2.Demo1.dataFormat(remainFlow * 1.0 / 1024)
                    + "GB");
        } else if (pack instanceof SuperPackage) {
            SuperPackage cardPack = (SuperPackage) pack;
            remaintalkTime = cardPack.getTalkTime() > demo2
                    .getRealTalkTime() ? cardPack.getTalkTime()
                    - demo2.getRealTalkTime() : 0;
            meg.append("通话时长：" + remaintalkTime + "分钟\n");
            remainSmsCount = cardPack.getSmsCount() > demo2
                    .getRealSMSCount() ? cardPack.getSmsCount()
                    - demo2.getRealSMSCount() : 0;
            meg.append("短信条数：" + remainSmsCount + "条\n");
            remainFlow = cardPack.getFlow() > demo2.getRealFlow() ? cardPack
                    .getFlow() - demo2.getRealFlow() : 0;
            meg.append("上网流量：" + task1205.Demo.Demo2.Demo1.dataFormat(remainFlow * 1.0 / 1024)
                    + "GB");
        }
        System.out.println(meg);
    }

    public void showAmountDetail(String searchNumber) {
        Demo2 demo2;
        StringBuffer meg = new StringBuffer();
        demo2 = demo2Map.get(searchNumber);
        meg.append("您的卡号：" + demo2.getCardNumber() + ",当月账单：\n");
        meg.append("套餐资费：" + demo2.getSerPackage().getPrice() + "元\n");
        meg.append("合计：" + task1205.Demo.Demo2.Demo1.dataFormat(demo2.getConsumAmount()) + "元\n");
        meg.append("账户余额：" + task1205.Demo.Demo2.Demo1.dataFormat(demo2.getMoney()) + "元");
        System.out.println(meg);
    }

    public void changingPack(String number, String packNum) {
        Demo2 demo2;
        SercicePackage pack;
        if (isExistCard(number)) {
            demo2 = demo2Map.get(number);
            switch (packNum) {
                case "1":
                    pack = new TalkPackage();
                    break;
                case "2":
                    pack = new NetPackage();
                    break;
                default:
                    pack = new SuperPackage();
                    break;
            }
            if (!(demo2.getSerPackage().getClass().getName().equals(pack.getClass().getName()))) {

                if (demo2.getMoney() >= pack.getPrice()) {
                    demo2.setMoney(demo2.getMoney() - pack.getPrice());
                    demo2.setSerPackage(pack);
                    demo2.setRealTalkTime(0);
                    demo2.setRealFlow(0);
                    demo2.setRealSMSCount(0);

                    demo2.setConsumAmount(pack.getPrice());
                    System.out.print("更换套餐成功！");
                    pack.ShowInfo();
                } else {
                    System.out.println("对不起，您的余额不足以支付新套餐本月资费，请充值后再办理更换套餐业务！");
                    return;
                }
            } else {
                System.out.println("对不起，您已经是该套餐用户，无需换套餐！");
            }

        } else {
            System.out.println("对不起，该卡号未注册，不能换套餐！");
        }
    }
    public void chargeMoney(String number, double money) {
        Demo2 demo2;
        if (money < 50) {
            System.out.println("对不起，最低充值金额为50元！");
            return;
        }
        demo2 = demo2Map.get(number);
        demo2.setMoney(demo2.getMoney() + money);
        System.out.println("充值成功，当前话费余额为" + Demo1.dataFormat(demo2.getMoney()) + "元。");
    }

    public void addConsumInfo(String number, task1205.Demo.Demo3.Demo1 info) {
        Set<String> numbers = demo1Map.keySet();
        Iterator<String> it = numbers.iterator();
        List<task1205.Demo.Demo3.Demo1> infos = new ArrayList<task1205.Demo.Demo3.Demo1>();
        boolean isExist = false;
        while (it.hasNext()) {
            if (it.next().equals(number)) {
                infos = demo1Map.get(number);
                infos.add(info);
                isExist = true;
                System.out.println("已添加一条消费记录。");
                break;
            }
        }

        if (!isExist) {
            infos.add(info);
            demo1Map.put(number, infos);
            System.out.println("不存在此卡的消费记录，已添加一条消费记录。");
        }
    }

    public void printConsumInfo(String number){
        Writer fileWriter = null;
        try {
            fileWriter = new FileWriter(number+"消费记录.txt");
            Set<String> numbers = demo1Map.keySet();
            Iterator<String> it = numbers.iterator();
            List<task1205.Demo.Demo3.Demo1> infos = new ArrayList<>();
            boolean isExist = false;
            while (it.hasNext()) {
                if (it.next().equals(number)) {
                    infos = demo1Map.get(number);
                    isExist = true;
                    break;
                }
            }
            if(isExist){
                StringBuffer content = new StringBuffer("******"+number+"消费记录******\n");
                content.append("序号\t类型\t数据（通话（条）/上网（MB）/短信（条））\n");
                for(int i=0;i<infos.size();i++){
                    task1205.Demo.Demo3.Demo1 info = infos.get(i);
                    content.append((i+1)+".\t"+info.getType()+"\t"+info.getConsumData()+"\n");
                }
                fileWriter.write(content.toString());
                fileWriter.flush();

                System.out.println("消费记录打印完毕！");
            }else{
                System.out.println("对不起，不存在此号码的消费记录，不能打印！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void userSoso(String number)  {
        Demo2 card = demo2Map.get(number);
        SercicePackage pack = card.getSerPackage();
        Random random = new Random();
        int ranNum = 0;
        int temp = 0;
        do{

            ranNum = random.nextInt(6);
            Demo3 scene = demo3s.get(ranNum);
            switch (ranNum) {
                case 0:
                case 1:
                    if (pack instanceof CallService) {
                        System.out.println(scene.getDescription());
                        CallService callService = (CallService) pack;
                        try {
                            temp = callService.call(scene.getData(), card);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        addConsumInfo(number, new task1205.Demo.Demo3.Demo1(number,
                                scene.getType(), temp));
                        break;
                    } else {
                        continue;
                    }
                case 2:
                case 3:
                    if (pack instanceof SendService) {
                        System.out.println(scene.getDescription());
                        SendService sendService = (SendService) pack;
                        try {
                            temp = sendService.sendMessage(scene.getData(), card);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        addConsumInfo(number, new task1205.Demo.Demo3.Demo1(number,
                                scene.getType(), temp));
                        break;
                    } else {
                        continue;
                    }

                case 4:
                case 5:
                    if (pack instanceof NetService) {
                        System.out.println(scene.getDescription());
                        NetService netService = (NetService) pack;
                        try {
                            temp = netService.netPlay(scene.getData(), card);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        addConsumInfo(number, new task1205.Demo.Demo3.Demo1(number,
                                scene.getType(), temp));
                        break;
                    } else {
                        continue;
                    }
            }
            break;
        }while(true);
    }

    public SercicePackage createPack(int packId) {
        SercicePackage pack = null;
        switch (packId) {
            case 1:
                pack = new TalkPackage();
                break;
            case 2:
                pack = new NetPackage();
                break;
            case 3:
                pack = new SuperPackage();
                break;
        }
        return pack;
    }


    public void showDescription(){
        Reader rd = null;
        try {
            rd = new FileReader("套餐资费说明.txt");
            char[] content = new char[1024];
            int len = 0;
            StringBuffer sb = new StringBuffer();
            while((len=rd.read(content))!=-1){
                sb.append(content,0,len);
            }
            System.out.println(sb);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
